package com.starsky.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * Jwt工具类
 */
public class JwtUtils {
    private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
    //生成token颜值
    public static String SECRET = "f4e2e52034348f86b67cde5[www.starsky.io]";
    // #token有效时长，默认7天，单位秒
    public static int EXPIRE = 604800;

    /**
     * @desc: 生成jwt token
     * @author: wangsh
     * @time: 2021/4/17 15:40
     * @userId: 用户id
     * @issuedDate: 使用时间
     * @expire: 过期时间
     */
    public String generateToken(Long userId, Date issuedDate, int expire) {
        if (issuedDate == null) {
            issuedDate = new Date();
        }
        Date date = DateUtils.addDateSecond(issuedDate, expire);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(issuedDate)
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    /**
     * 生成jwt token
     */
    public static String generateToken(Long userId, int expire) {
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(userId + "")
                .setIssuedAt(new Date())
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    public static Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            logger.debug("validate is token error, token = " + token, e);
            return null;
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }
}
